﻿using Microsoft.AspNetCore.Http;
using System;
using WYJCore;
using WYJCore.Extension;
using WYJCore.Web;
using WYJData.DatabaseAccess;

namespace WYJWeb
{
    public abstract class ControllerBase<TModel> where TModel : class, IModel, new()
    {
        public ControllerBase()
        {
            Db = new Database();
        }
        public HttpContext CurrentHttpContext { get; set; }
        public Database Db { get; }

        public virtual string BaseWhere(string key)
        {
            return null;
        }
        public virtual string MakeWhere(string key)
        {
            return key.IsNullOrEmpty() ? null : BaseWhere(key);
        }

        public virtual Response GetList(string key, int pageIndex, int pageSize)
        {
            return Respond(db =>
            {
                return db.GetPageList<TModel>(pageIndex, pageSize, BaseWhere(key));
            });
        }

        public virtual Response GetModel(int id)
        {
            return Respond(db =>
            {
                return db.GetModelById<TModel>(id);
            });
        }


        public Response Save(string Form)
        {
            return Respond(db =>
            {
                TModel model = Newtonsoft.Json.JsonConvert.DeserializeObject<TModel>(Form);
                if (model.Id > 0) db.Update(model);
                else db.Insert(model);
            });
        }



        internal virtual void AfterSave(TModel model)
        {

        }

        internal virtual void BeforeSave(TModel model) { }

        protected Response Respond(Func<Database, object> func, string msg = null)
        {
            return new Response
            {
                Data = func(Db),
                IsSuccess = true,
                Msg = msg
            };
        }
        protected Response Respond(Action<Database> action, string msg = null)
        {
            action(Db);
            return new Response
            {
                IsSuccess = true,
                Msg = msg
            };
        }
    }
}
